package com.lsb.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lsb.mapper.UserMapper;
import com.lsb.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：liusibo
 * @description：TODO
 * @date ：2021/6/9 23:10
 */
@Service(value = "userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //判断学号非空
        if(StrUtil.isEmpty(username)){
            throw new RuntimeException("用户名不能为空");
        }

        //如果不为空,则从数据库中通过用户名获取对应的用户信息 用了 mybatisPlus 的 mapper自带查询方法
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //查找是否存在该学号/工号的用户
        wrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(wrapper);
        System.out.println(user);
        if(user==null){
            //被锁定的账户会走这里，统一显示密码错误给前端
            throw new UsernameNotFoundException("该用户不存在!");
        }
        //如果用户存在则要查询用户的角色集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        //数据库表设计的比较简单，一个用户user只对应一个角色role
        String role = user.getRole();
        //如果数据库角色字段中没有添加ROLE_则这里需要手动添加一个
        //SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_"+role);
        authorities.add(new SimpleGrantedAuthority(role));
        //账户可用
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}

